package priv.cwr.springboot.demo.service;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import priv.cwr.springboot.demo.component.Errors;
import priv.cwr.springboot.demo.exception.ApiException;
import priv.cwr.springboot.demo.mapper.DeptMapper;
import priv.cwr.springboot.demo.model.db.DeptEntity;
import priv.cwr.springboot.demo.model.vo.base.Result;

/**
 * User: R
 * Date: 2018/8/30
 * Time: 9:17
 * Created with IntelliJ IDEA.
 */
@Service
public class DeptService {
    private final Errors errors;
    private final DeptMapper deptMapper;

    public DeptService(Errors errors,
                       DeptMapper deptMapper) {
        this.errors = errors;
        this.deptMapper = deptMapper;
    }

    /**
     * 添加部门
     *
     * @param deptEntity 部门实体
     * @return 部门id
     */
    @Transactional
    public long addDept(DeptEntity deptEntity) {
        try {
            this.deptMapper.insert(deptEntity);
            return deptEntity.getDeptId();
        } catch (Exception e) {
            // 配合Transactional手动让spring回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new ApiException("添加部门失败", new Result(errors, 1002, HttpStatus.INTERNAL_SERVER_ERROR.value(), "添加"));
        }
    }
}
